package dao

import (
	"context"
	"gorm.io/gorm"
	"mall_2.0/pkg/utils/log"
	"mall_2.0/respository/db/model"
)

type UserDao struct {
	*gorm.DB
}

func NewUserDao(ctx context.Context) *UserDao {
	return &UserDao{NewDBClient(ctx)}
}

func NewUserDaoByDB(db *gorm.DB) *UserDao {
	return &UserDao{db}
}

// ExistOrNotByUserName 根据username判断用户是否存在
func (dao *UserDao) ExistOrNotByUserName(userName string) (user *model.User, exist bool, err error) {
	var count int64
	err = dao.DB.Model(&model.User{}).Where("user_name = ?", userName).Count(&count).Error
	if count == 0 {
		return user, false, err
	}
	err = dao.DB.Model(&model.User{}).Where("user_name = ?", userName).First(&user).Error
	if err != nil {
		return user, false, err
	}
	return user, true, nil
}

// CreateUser 创建用户
func (dao *UserDao) CreateUser(user *model.User) error {
	return dao.DB.Model(&model.User{}).Create(user).Error
}

// GetUserById 根据 ID 获取用户
func (dao *UserDao) GetUserById(uId uint) (user *model.User, err error) {
	err = dao.DB.Model(&model.User{}).Where("id = ?", uId).First(&user).Error
	return
}

// UpdateUserById 根据 ID 更新用户信息
func (dao *UserDao) UpdateUserById(uId uint, user *model.User) error {
	return dao.DB.Model(&model.User{}).Where("id = ?", uId).Updates(&user).Error
}

// ListFollower 展示关注者
func (dao *UserDao) ListFollower(uId uint) (f []*model.User, err error) {
	u, f := new(model.User), make([]*model.User, 0)
	err = dao.DB.Model(&model.User{}).Where("id = ?", uId).First(&u).Error
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	err = dao.DB.Model(&u).Association("Relations").Find(&f)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	return
}

// FollowUser 关注用户
func (dao *UserDao) FollowUser(uId, fId uint) (err error) {
	u, f := new(model.User), new(model.User)
	err = dao.DB.Model(&model.User{}).Where("id = ?", uId).First(&u).Error
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	err = dao.DB.Model(&model.User{}).Where("id = ?", fId).First(&f).Error
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	err = dao.DB.Model(&f).Association("Relations").Append([]model.User{*u})
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	return
}

// UnFollowUser 取关用户
func (dao *UserDao) UnFollowUser(uId, fId uint) (err error) {
	u, f := new(model.User), new(model.User)
	err = dao.DB.Model(&model.User{}).Where("id = ?", uId).First(&u).Error
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	err = dao.DB.Model(&model.User{}).Where("id = ?", fId).First(&f).Error
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	err = dao.DB.Model(&u).Association("Relations").Delete(f)
	if err != nil {
		log.LogrusObj.Error(err)
		return
	}
	return
}
